<?php

class treeComponents extends sfComponents
{
    public function executeCulture()
    {
        $returnUrl = $this->getModuleName() . '/' . $this->getActionName();
        if( ($id = (int)$this->getRequestParameter('id', 0)) )
        {
            $returnUrl .= '?id=' . $id;
        }
        // TODO: move to system module
        $this->setFlash('returnUrl',$returnUrl);
    }
   public function executeMain_menu()
    {
        $arTree = Tree::getTree($this->parent, sfContext::getInstance()->getUser()->getCulture());
        //$arTree = Tree::getTreeByLabel('ROOT', sfContext::getInstance()->getUser()->getCulture());
        //debugvar($arTree);
        $this->arTree = $arTree[0]['children'];
        
    }
   public function executeCategories()
    {
        $id = $this->getRequestParameter('id', 0);
        $products = Tree::getByLabel('PRODUCTS');
        $tree = TreePeer::retrieveByPK($id);
        if($tree && (preg_match("/\b" . (int)$products->getId() . "\b/", $tree->getBranch()) || $tree->getLabel() == 'PRODUCTS'))
        {
            if( $tree->getLabel()!= 'PRODUCTS' )
            {
                $parent = Tree::getParentByChild($tree->getId());
                if( $parent )
                {
                    if( ($parent->getLabel() == 'PRODUCTS') )
                    {
                        $rightParent = true;
                        $parentId = $id;
                    }else 
                    {
                        $parentId = $tree->getParentId();
                    }
                }
            }else 
            {
                $main = Tree::getTreeByLabel('PRODUCTS', sfContext::getInstance()->getUser()->getCulture());
                if( $main[0]['children'][0]['obj'] )
                {
                    $parentId = $main[0]['children'][0]['obj']->getId();
                }
            }
        }
        if(isset($parentId))
        {
            $this->parentId = $parentId;
            $treeforName= TreePeer::retrieveByPK($parentId);
            $this->treeName = $treeforName->getName();
            $subCategories = Tree::getTree($parentId, get_culture());
            $this->subCategories  = $subCategories[0]['children'];
        }
        
    }
    public function executeBranch()
    {
        $this->userCulture = $this->getUser()->getCulture();
        $arBranch = Tree::getTree($this->tree->getId(), $this->userCulture);

        // Root element
        $this->level = 1;
        if( $arBranch[0] )
        {
            $this->arBranch = $arBranch;
        }else
            $this->arBranch = array();
    }


    public function executeParent_branch()
    {
        $this->userCulture = $this->getUser()->getCulture();

        if( $objId = (int)$this->getRequestParameter('id', 0) )
        {
            $obj = Tree::getById($objId);
            $this->arParents = Tree::getBranchById($objId, $this->userCulture);
        }

    }
    

}